import { HttpError } from "./error";
import { CasbinHandler, usePlugin } from "./plugin";

export const useRbac = <T>(h: CasbinHandler<T>): Promise<T> => {
    return usePlugin('@sker/casbin', h)
}

export const useUserRoles = async (username: string) => {
    return await useRbac(async h => {
        return await h.getRolesForUser(username)
    })
}

export const useRoleUsers = async (role: string) => {
    return await useRbac(async h => {
        return await h.getUsersForRole(role)
    })
}

export const useHasRole = async (name: string, role: string) => {
    return await useRbac(async h => {
        return await h.hasRoleForUser(name, role)
    })
}
export const useAddRole = async (name: string, role: string) => {
    return await useRbac(async h => {
        return await h.addRoleForUser(name, role)
    })
}

export const useDelRole = async (name: string, role: string) => {
    return await useRbac(async h => {
        return await h.deleteRoleForUser(name, role)
    })
}

export const useUserPermissions = async (name: string) => {
    return await useRbac(async h => {
        return await h.getPermissionsForUser(name)
    })
}


export const updateRbac = async (groupId: string, addUser: string, removeUser?: string) => {
    await useRbac(async r => {
        if (!groupId) throw new HttpError(`没有设置管理端用户`)
        if (removeUser) {
            await r.deleteRoleForUser(removeUser, groupId)
        }
        if (addUser) {
            await r.addRoleForUser(addUser, groupId)
        }
        await r.savePolicy();
    })
}